#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //新增行
    ui->tableWidget_2->insertRow(0);//默认的即可不用设置行名称
    ui->tableWidget_2->insertRow(1);
    ui->tableWidget_2->insertRow(2);

    //新增列
    ui->tableWidget_2->insertColumn(0);
    ui->tableWidget_2->setHorizontalHeaderItem(0,new QTableWidgetItem("学号"));
    ui->tableWidget_2->insertColumn(1);
    ui->tableWidget_2->setHorizontalHeaderItem(1,new QTableWidgetItem("姓名"));
    ui->tableWidget_2->insertColumn(2);
    ui->tableWidget_2->setHorizontalHeaderItem(2,new QTableWidgetItem("年龄"));

    //添加数据
    ui->tableWidget_2->setItem(0,0,new QTableWidgetItem("1"));
    ui->tableWidget_2->setItem(0,1,new QTableWidgetItem("张三"));
    ui->tableWidget_2->setItem(0,2,new QTableWidgetItem("20"));

    ui->tableWidget_2->setItem(1,0,new QTableWidgetItem("2"));
    ui->tableWidget_2->setItem(1,1,new QTableWidgetItem("李四"));
    ui->tableWidget_2->setItem(1,2,new QTableWidgetItem("28"));

    ui->tableWidget_2->setItem(2,0,new QTableWidgetItem("3"));
    ui->tableWidget_2->setItem(2,1,new QTableWidgetItem("王五"));
    ui->tableWidget_2->setItem(2,2,new QTableWidgetItem("88"));



}

Widget::~Widget()
{
    delete ui;
}

//新增一列
void Widget::on_pushButton_clicked()
{
    //获取LineEdit中的文本
    QString text = ui->lineEdit->text();

    //获取当前列数
    int ccount = ui->tableWidget->columnCount();
    //添加新列
    ui->tableWidget->insertColumn(ccount);//添加的是下标，所以刚好和个数相同

    //添加列名称
    if(text != nullptr){
        ui->tableWidget->setHorizontalHeaderItem(ccount,new QTableWidgetItem(text));
    }
}

//删除选择的列
void Widget::on_pushButton_2_clicked()
{
    //获取光标选中的列
    int ccolumn = ui->tableWidget->currentColumn();
    //删除
    ui->tableWidget->removeColumn(ccolumn);
}

//新增一行
void Widget::on_pushButton_3_clicked()
{
    //获取LineEdit中的文本
    QString text = ui->lineEdit->text();
    //获取当前行数
    int rcount = ui->tableWidget->rowCount();
    //添加新行
    ui->tableWidget->insertRow(rcount);//添加的是下标，所以刚好和个数相同

    //添加行名称
    if(text != ""){
        ui->tableWidget->setVerticalHeaderItem(rcount,new QTableWidgetItem(text));
    }
}


//删除选中的行
void Widget::on_pushButton_4_clicked()
{
    //获取光标选中的行
    int crow = ui->tableWidget->currentRow();
    //删除行
    ui->tableWidget->removeRow(crow);
}
